package com.listeningframework.boot.autoconfigure.webmvc.validate;

import java.util.Arrays;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * Bytes Length Validator
 * @author lixining
 * @version $Id: BytesValidator.java, v 0.1 2016年5月5日 下午4:19:01 lixining Exp $
 */
public class ListeningContainsValidator implements ConstraintValidator<ListeningContains, String> {
    /**
     * Error Message
     */
    private String   message;
    /**
     * Source Allowed Options
     */
    private String[] src;

    /**
     * @see javax.validation.ConstraintValidator#initialize(java.lang.annotation.Annotation)
     */
    @Override
    public void initialize(ListeningContains constraintAnnotation) {
        this.src = constraintAnnotation.src();
        this.message = constraintAnnotation.message();
    }

    /**
     * @see javax.validation.ConstraintValidator#isValid(java.lang.Object, javax.validation.ConstraintValidatorContext)
     */
    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (Arrays.asList(src).contains(value)) {
            return true;
        }
        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate(message).addConstraintViolation();
        return false;
    }

}
